package com.zhongxi.guoyuan.OffLineShop;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.zhongxi.guoyuan.OffLineShop.Adapter.ShopListAdapter;
import com.zhongxi.guoyuan.OffLineShop.Model.ItemShopInfo;
import com.zhongxi.guoyuan.OffLineShop.UI.OffLineCateActivity;
import com.zhongxi.guoyuan.OffLineShop.UI.OffLineSearchActivity;
import com.zhongxi.guoyuan.OffLineShop.UI.OffLineShopDetailActivtiy;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.adapter.CategoryAdapter;
import com.zhongxi.guoyuan.adapter.ImageBannerAdapter;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.entity.ad.AdData;
import com.zhongxi.guoyuan.entity.ad.AdResult;
import com.zhongxi.guoyuan.entity.projectItem.ProjectItemData;
import com.zhongxi.guoyuan.entity.projectItem.ProjectItemResult;
import com.zhongxi.guoyuan.utils.CommonTool;
import com.zhongxi.guoyuan.utils.Constants;
import com.zhongxi.guoyuan.utils.ImageUtils;
import com.zhongxi.guoyuan.utils.SpUtils;
import com.zhongxi.guoyuan.utils.ToastUtil;
import com.zhongxi.guoyuan.utils.UiUtils;
import com.zhongxi.guoyuan.view.MainHomeActivity;
import com.zhongxi.guoyuan.view.seller.offline.AddParameter;
import com.zhongxi.guoyuan.widget.CircleIndicator;
import com.zhongxi.guoyuan.widget.ViewFlow;
import com.zhongxi.guoyuan.widget.goldshop.NoScrollGridView;
import com.zhongxi.guoyuan.widget.view.MyScrollView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;

/**
 * Created by Administrator on 2018/1/5.
 */

public class OffLineShopFragment extends OffLineBaseFragment implements MyScrollView.OnScrollListener {

    @Bind(R.id.ivBack)
    ImageView ivBack;
    @Bind(R.id.tvTitle)
    TextView tvTitle;
    @Bind(R.id.linearStop)
    LinearLayout linearStop;
    @Bind(R.id.viewflow)
    ViewFlow viewflow;
    @Bind(R.id.viewflowdic)
    CircleIndicator viewflowdic;
    @Bind(R.id.flow)
    FrameLayout flow;
    @Bind(R.id.search_offline)
    LinearLayout searchOffline;
    @Bind(R.id.ll_search)
    LinearLayout llSearch;
    @Bind(R.id.tv_recommend)
    TextView tvRecommend;
    @Bind(R.id.tv_distance)
    TextView tvDistance;
    @Bind(R.id.tv_popularity)
    TextView tvPopularity;
    @Bind(R.id.scrollBody)
    LinearLayout scrollBody;
    @Bind(R.id.linearBegin)
    LinearLayout linearBegin;
    @Bind(R.id.recycleView_offLine)
    RecyclerView recycleViewOffLine;
    @Bind(R.id.linearLayout)
    LinearLayout linearLayout;
    @Bind(R.id.rl_progressbar)
    RelativeLayout mRlProgressbar;
    @Bind(R.id.myScrollView)
    MyScrollView mMyScrollView;
    @Bind(R.id.tv_store_cate)
    TextView mTvStoreCate;
    @Bind(R.id.page_bt)
    Button mPageBt;
    @Bind(R.id.fl_error_view)
    FrameLayout mFlErrorView;
    @Bind(R.id.emptyView)
    FrameLayout mEmptyView;
    private boolean isMeasured;

    private int measuredHeight;
    private ImageBannerAdapter imageBannerAdapter;
    private int orderBy = 1;
    private String cateid = "0";
    private PopupWindow popupWindow;
    private ArrayList<ProjectItemData> mProjectItemDataList = new ArrayList<>();
    private List<ItemShopInfo> mShopInfoList = new ArrayList<>();
    private ShopListAdapter mAdapter;
    private boolean mIsLoadMore;

    @Override
    protected View init() {
        View mView = UiUtils.inflate(R.layout.fragment_offline);
        ButterKnife.bind(this, mView);
        return mView;
    }

    @Override
    protected void initView(View view) {
        super.initView(view);
        tvTitle.setText(R.string.title_offLine);
        mRlProgressbar.setVisibility(View.VISIBLE);
        mFlErrorView.setVisibility(View.INVISIBLE);
        mMyScrollView.setVisibility(View.INVISIBLE);
        ImageUtils.setHeight(getActivity(), Constants.flowRate, flow);
        ViewTreeObserver observer = linearLayout.getViewTreeObserver();
        observer.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                if (!isMeasured) {
                    measuredHeight = linearLayout.getMeasuredHeight();
                    isMeasured = true;
                }
                return true;
            }
        });
        recycleViewOffLine.setLayoutManager(new LinearLayoutManager(UiUtils.getContext()));
        recycleViewOffLine.setNestedScrollingEnabled(false);
        if (mAdapter == null) {
            mAdapter = new ShopListAdapter(mShopInfoList, 0);
            recycleViewOffLine.setAdapter(mAdapter);
        }
    }

    @Override
    protected void initNet() {
        super.initNet();
        netWorkAd();
    }

    private void netWorkAd() {
        unsubscribe();
        mDisposable = Observable.concat(AddParameter.getInstance().getAdData(5), AddParameter.getInstance().getStoreCate(),
                AddParameter.getInstance().getStoreList(page, orderBy, cateid))
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        mProjectItemDataList.clear();
                        ProjectItemData mProjectItemData = new ProjectItemData("0", "全部", "", false);
                        mProjectItemDataList.add(mProjectItemData);
                        mShopInfoList.clear();
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer() {
                    @Override
                    public void accept(Object o) throws Exception {
                        if (o instanceof AdResult) {
                            AdResult adResult = (AdResult) o;
                            MyApplication.getInstance().setSpValue(adResult.getSafeobj());
                            if (adResult.getCode() == 1) {
                                viewflow.setFlowIndicator(viewflowdic);
                                List<AdData> mDataList = adResult.getData();
                                if (mDataList != null && mDataList.size() > 0) {
                                    viewflow.setSideBuffer(mDataList.size());
                                } else {
                                    viewflow.setSideBuffer(0);
                                }
                                if (imageBannerAdapter == null) {
                                    imageBannerAdapter = new ImageBannerAdapter(getActivity(), mDataList, 3);
                                    viewflow.setAdapter(imageBannerAdapter);
                                } else {
                                    imageBannerAdapter.replaceAll(mDataList);
                                }
                                viewflow.startAutoFlowTimer();
                            } else if (adResult.getCode() == 2816) {
                                logoutDialog();
                            } else {
                                ToastUtil.show(getString(R.string.loseData, adResult.getCode()));
                            }
                        } else if (o instanceof ProjectItemResult) {
                            ProjectItemResult projectItemResult = (ProjectItemResult) o;
                            MyApplication.getInstance().setSpValue(projectItemResult.getSafeobj());
                            if (projectItemResult.getCode() == 1) {
                                mProjectItemDataList.addAll(projectItemResult.getData());
                            } else if (projectItemResult.getCode() == 2816) {
                                logoutDialog();
                            } else {
                                ToastUtil.show(getString(R.string.loseData, projectItemResult.getCode()));
                            }
                        } else {
                            if (page == 1) {
                                mShopInfoList.clear();
                            }
                            ResponseBody responseBody = (ResponseBody) o;
                            JSONObject jsonObject = new JSONObject(responseBody.string());
                            JSONObject safeobj = jsonObject.optJSONObject("safeobj");
                            MyApplication.getInstance().sharedPrefrences.edit().putString("now", safeobj.optString("now")).commit();
                            MyApplication.getInstance().sharedPrefrences.edit().putString("sk", safeobj.optString("safestring")).commit();
                            int mCode = jsonObject.optInt("code");
                            if (mCode == 1) {
                                JSONArray mJSONArray = jsonObject.optJSONArray("data");
                                JSONObject mObject = jsonObject.optJSONObject("cateInfo");
                                if (mJSONArray != null && mJSONArray.length() > 0) {
                                    for (int i = 0; i < mJSONArray.length(); i++) {
                                        ItemShopInfo mItemShopInfo = ItemShopInfo.getParseObject((JSONObject) mJSONArray.get(i));
                                        String mCateName = mObject.optString(((JSONObject) mJSONArray.get(i)).optString("cateid"));
                                        mItemShopInfo.setCateName(mCateName);
                                        mShopInfoList.add(mItemShopInfo);
                                    }
                                    mAdapter.notifyDataSetChanged();
                                    mAdapter.setLoadingState(mAdapter.LOADCOMPLENT);
                                    mIsLoadMore = true;
                                } else {
                                    if (page > 1) {
                                        mAdapter.setLoadingState(mAdapter.LOADEND);
                                        page--;
                                    }
                                    mIsLoadMore = false;
                                }
                            } else if (mCode == 2816) {
                                logoutDialog();
                                mIsLoadMore = false;
                            } else {
                                if (page > 1) {
                                    page--;
                                }
                                ToastUtil.show(getString(R.string.loseData, mCode));
                                mIsLoadMore = false;
                            }
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        mIsLoadMore = false;
                        mFlErrorView.setVisibility(View.VISIBLE);
                        mRlProgressbar.setVisibility(View.INVISIBLE);
                        mPageBt.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                mFlErrorView.setVisibility(View.INVISIBLE);
                                mRlProgressbar.setVisibility(View.VISIBLE);
                                netWorkAd();
                            }
                        });
                    }
                }, new Action() {
                    @Override
                    public void run() throws Exception {
                        mFlErrorView.setVisibility(View.INVISIBLE);
                        mRlProgressbar.setVisibility(View.INVISIBLE);
                        mMyScrollView.setVisibility(View.VISIBLE);
                        if (mShopInfoList.size() > 0) {
                            mEmptyView.setVisibility(View.INVISIBLE);
                            recycleViewOffLine.setVisibility(View.VISIBLE);
                        } else {
                            mEmptyView.setVisibility(View.VISIBLE);
                            recycleViewOffLine.setVisibility(View.INVISIBLE);
                        }
                    }
                });
    }

    private void logoutDialog() {
        final AlertDialog mDialog = new AlertDialog.Builder(getActivity()).create();
        View view = UiUtils.inflate(R.layout.dialog_logout);
        TextView tv_Iknow = (TextView) view.findViewById(R.id.tv_Iknow);
        tv_Iknow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
                clearData();
            }
        });
        mDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (mDialog != null && mDialog.isShowing()) {
                        mDialog.dismiss();
                        clearData();
                    }
                    return true;
                }
                return false;
            }
        });
        mDialog.setCanceledOnTouchOutside(false);
        mDialog.setView(view);
        mDialog.show();
    }

    private void clearData() {
        if (null != MyApplication.getInstance().getUserId() || !"".equals(MyApplication.getInstance().getUserId())) {
            MyApplication.getInstance().sharedPrefrences.edit().putString("phone", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("userid", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("username", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("shopname", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("rmb", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("silver", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("inner", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("hd", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("num", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("avatar", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putBoolean("shareHolder", false).commit();
            MyApplication.getInstance().sharedPrefrences.edit().putBoolean("privilege", false).commit();
            MyApplication.getInstance().sharedPrefrences.edit().putBoolean("beneficiary", false).commit();
            MyApplication.getInstance().sharedPrefrences.edit().putBoolean("merchants", false).commit();

            MyApplication.getInstance().sharedPrefrences.edit().putString("avatar", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("rewardName", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("rewardUserphone", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("rewardAddress", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("rewardAddressid", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("appopenid", "").commit();
            SpUtils.getInstance().saveSp("shopid", "");
            SpUtils.getInstance().saveSp("mdffline", "");
            SpUtils.getInstance().saveSp("orderid", "");
            getActivity().finish();
            startActivity(new Intent(UiUtils.getContext(), MainHomeActivity.class));
        }
    }

    @Override
    protected void initListener() {
        super.initListener();
        mMyScrollView.setOnScrollListener(this);
        mAdapter.setOnItemClickListener(new ShopListAdapter.OnItemClickListener() {
            @Override
            public void onItemClickListener(View view, int position) {
                Intent mIntent = new Intent(UiUtils.getContext(), OffLineShopDetailActivtiy.class);
                mIntent.putExtra("offlineshopid", mShopInfoList.get(position).getId());
                startActivity(mIntent);
            }
        });
    }

    @OnClick({R.id.ivBack, R.id.search_offline, R.id.ll_search, R.id.tv_recommend, R.id.tv_distance, R.id.tv_popularity})
    public void onViewClicked(final View view) {
        switch (view.getId()) {
            case R.id.ivBack:
                getActivity().finish();
                break;
            case R.id.search_offline:
//                getPopupwindow(view);
                Intent mIntent = new Intent(UiUtils.getContext(), OffLineCateActivity.class);
                mIntent.putExtra("catelist", mProjectItemDataList);
                startActivity(mIntent);
                break;
            case R.id.ll_search:
                startActivity(new Intent(getActivity(), OffLineSearchActivity.class));
                break;
            case R.id.tv_recommend:
                if (scrollBody.getParent() != linearBegin) {
                    mMyScrollView.fullScroll(MyScrollView.FOCUS_UP);
                    linearStop.removeView(scrollBody);
                    linearBegin.addView(scrollBody);
                }
                tvRecommend.setTextColor(getResources().getColor(R.color.title_red));
                tvDistance.setTextColor(getResources().getColor(R.color.gohere));
                tvPopularity.setTextColor(getResources().getColor(R.color.gohere));
                page = 1;
                orderBy = 1;
                getShopList();
                break;
            case R.id.tv_distance:
                if (scrollBody.getParent() != linearBegin) {
                    mMyScrollView.fullScroll(MyScrollView.FOCUS_UP);
                    linearStop.removeView(scrollBody);
                    linearBegin.addView(scrollBody);
                }
                tvRecommend.setTextColor(getResources().getColor(R.color.gohere));
                tvDistance.setTextColor(getResources().getColor(R.color.title_red));
                tvPopularity.setTextColor(getResources().getColor(R.color.gohere));
                page = 1;
                orderBy = 2;
                getShopList();
                break;
            case R.id.tv_popularity:
                if (scrollBody.getParent() != linearBegin) {
                    mMyScrollView.fullScroll(MyScrollView.FOCUS_UP);
                    linearStop.removeView(scrollBody);
                    linearBegin.addView(scrollBody);
                }
                tvRecommend.setTextColor(getResources().getColor(R.color.gohere));
                tvDistance.setTextColor(getResources().getColor(R.color.gohere));
                tvPopularity.setTextColor(getResources().getColor(R.color.title_red));
                page = 1;
                orderBy = 3;
                getShopList();
                break;
        }
    }

    private void getPopupwindow(View v) {
        View popView = View.inflate(getActivity(), R.layout.pop_reward_window, null);
        WindowManager wm = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth() * 10 / 11;
        int height = wm.getDefaultDisplay().getHeight() / 3;
        popView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        popupWindow = new PopupWindow(popView, width, height, true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setFocusable(true);
        int[] location = new int[2];
        v.getLocationInWindow(location);  //将v相对屏幕的坐标存入int数组中 int[0] 为 x轴 int[1]为y轴
        Animation animation = AnimationUtils.loadAnimation(getActivity(), R.anim.popupwindow);
        popView.startAnimation(animation);
        popupWindow.showAtLocation(v, Gravity.NO_GRAVITY, location[0] + v.getWidth() / 10, location[1] + v.getWidth() * 1 / 3);
        NoScrollGridView gv_category = (NoScrollGridView) popView.findViewById(R.id.gv_category);
        CategoryAdapter adapter = new CategoryAdapter(getActivity(), mProjectItemDataList);
        gv_category.setAdapter(adapter);
        gv_category.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                popupWindow.dismiss();
//                mTvStoreCate.setText(mProjectItemDataList.get(position).getName());
//                cateid = mProjectItemDataList.get(position).getId();
//                page = 1;
//                getShopList();
            }
        });
    }

    private void getShopList() {
        unsubscribe();
        mDisposable = AddParameter.getInstance().getStoreList(page, orderBy, cateid)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<ResponseBody>() {
                    @Override
                    public void accept(ResponseBody responseBody) throws Exception {
                        if (page == 1) {
                            mShopInfoList.clear();
                        }
                        JSONObject jsonObject = new JSONObject(responseBody.string());
                        JSONObject safeobj = jsonObject.optJSONObject("safeobj");
                        MyApplication.getInstance().sharedPrefrences.edit().putString("now", safeobj.optString("now")).commit();
                        MyApplication.getInstance().sharedPrefrences.edit().putString("sk", safeobj.optString("safestring")).commit();
                        int mCode = jsonObject.optInt("code");
                        if (mCode == 1) {
                            JSONArray mJSONArray = jsonObject.optJSONArray("data");
                            JSONObject mObject = jsonObject.optJSONObject("cateInfo");
                            if (mJSONArray != null && mJSONArray.length() > 0) {
                                for (int i = 0; i < mJSONArray.length(); i++) {
                                    ItemShopInfo mItemShopInfo = ItemShopInfo.getParseObject((JSONObject) mJSONArray.get(i));
                                    String mCateName = mObject.optString(((JSONObject) mJSONArray.get(i)).optString("cateid"));
                                    mItemShopInfo.setCateName(mCateName);
                                    mShopInfoList.add(mItemShopInfo);
                                }
                                mAdapter.notifyDataSetChanged();
                                mAdapter.setLoadingState(mAdapter.LOADCOMPLENT);
                                mIsLoadMore = true;
                            } else {
                                if (page > 1) {
                                    mAdapter.setLoadingState(mAdapter.LOADEND);
                                    page--;
                                }
                                mIsLoadMore = false;
                            }
                        } else if (mCode == 2816) {
                            logoutDialog();
                            mIsLoadMore = false;
                        } else {
                            if (page > 1) {
                                page--;
                            }
                            ToastUtil.show(getString(R.string.loseData, mCode));
                            mIsLoadMore = false;
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        mIsLoadMore = false;
                        if (page > 1) {
                            page--;
                        }
                        mMyScrollView.setVisibility(View.VISIBLE);
                        ToastUtil.show(getString(R.string.load_error_shopList));
                    }
                }, new Action() {
                    @Override
                    public void run() throws Exception {
                        if (mShopInfoList.size() > 0) {
                            mEmptyView.setVisibility(View.INVISIBLE);
                            recycleViewOffLine.setVisibility(View.VISIBLE);
                        } else {
                            mEmptyView.setVisibility(View.VISIBLE);
                            recycleViewOffLine.setVisibility(View.INVISIBLE);
                        }
                        mMyScrollView.setVisibility(View.VISIBLE);
                    }
                });
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onScroll(int scrollY) {
        if (scrollY >= measuredHeight) {
            if (scrollBody.getParent() != linearStop) {
                linearBegin.removeView(scrollBody);
                linearBegin.setLayoutParams(new LinearLayout.LayoutParams(scrollBody.getMeasuredWidth(), scrollBody.getMeasuredHeight()));
                linearStop.addView(scrollBody);
            }
        } else {
            if (scrollBody.getParent() != linearBegin) {
                linearStop.removeView(scrollBody);
                linearBegin.addView(scrollBody);
            }
        }
    }

    Handler mHandler = new Handler();

    @Override
    public void scrollBottom() {
        if (mIsLoadMore && CommonTool.isFirstScroll()) {
            mAdapter.setLoadingState(mAdapter.LOADING);
            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            page++;
                            getShopList();
                        }
                    });
                }
            }, 1000);
        }
    }
}
